var SimplejQueryDataTablesGadget = {

gadgetHelper : null,
gTableDiv : null,
gToolbar : null,
gResetBtn : null,
gSettingBtn : null,
gToggleBtn : null,
gTable : null,
gPrefs : null,

init : function(configMessages) {
  gTableDiv = $('#SimplejQueryDataTablesGadget_EnteredValuePicker_tableDiv');
  gMsges = configMessages;
  google.setOnLoadCallback(SimplejQueryDataTablesGadget.sendQuery);
},

sendQuery: function() {
  gPrefs = new _IG_Prefs();
  if( gPrefs.getString("title") != '' ) try {
      _IG_SetTitle( gPrefs.getString("title") );
  } catch(e) {}
  gadgetHelper = new google.visualization.GadgetHelper();
  gadgetHelper.createQueryFromPrefs(gPrefs).send(SimplejQueryDataTablesGadget.handleQueryResponse);
},

handleQueryResponse: function(response) {

  if (!gadgetHelper.validateResponse(response)) {
    gTableDiv.text('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
    return;
  }

  var data = response.getDataTable();
  if( ! data ) { return alert(response.getDetailedMessage); }

  var html = ['<table id="SimplejQueryDataTablesGadget_EnteredValuePicker_table" cellspacing="0"><thead><tr>'];
  for( var j = 0 ; j < data.getNumberOfColumns() ; j++ ) {
    html.push('<th>' + (data.getFormattedValue(0,j)||'&nbsp;') + '</th>');
  }
  html.push('</tr></thead><tbody>');
  for( var i = 1 ; i < data.getNumberOfRows() ; i++ ) {
    html.push('<tr>');
    for( var j = 0 ; j < data.getNumberOfColumns() ; j++ ) {
      html.push('<td>' + (data.getFormattedValue(i,j)||'&nbsp;') + '</td>');
    }
    html.push('</tr>');
  }
  $('#SimplejQueryDataTablesGadget_EnteredValuePicker_tableDiv').html( html.join('')+'</tbody></table>' );
  gTable = $('#SimplejQueryDataTablesGadget_EnteredValuePicker_table');
  gTable.dataTable({
    "bPaginate": false,
    "bInfo": false,
    "bLengthChange": false,
    "bSortClasses": false,
    "oLanguage": gMsges['dataTable_locale']
  }).find('tbody').height( gPrefs.getString("tbody_height")==0 ? '100%' : gPrefs.getString("tbody_height") );

  // settings
  gTable.find('thead th').each(function(i, dom){
    var html = '<option value="'+ i +'"' + ( $.inArray($(this).text(), gPrefs.getArray("filterable"))>-1 ? ' selected="selected"' : '' ) + '>'+ $(this).text() +'</option>';
    $('#pref_filterable').append(html);
  });
  $('#pref_tbody_height').val( gPrefs.getString("tbody_height") );
  $('#pref_submit').click(function(){
    var filterable = $('#pref_filterable').val() || [];
    gPrefs.setArray("filterable", filterable);
    gPrefs.set("tbody_height", $('#pref_tbody_height').val());
    $('#SimplejQueryDataTablesGadget_EnteredValuePicker_dropdown_wrapper').empty();
    buildDropDownFilters();
    gTable.find('tbody').height( gPrefs.getString("tbody_height")==0 ? '100%' : gPrefs.getString("tbody_height") );
  });

  $('.dataTables_filter').before('<form action="" id="SimplejQueryDataTablesGadget_EnteredValuePicker_toolbar"></form>');
  gToolbar = $('#SimplejQueryDataTablesGadget_EnteredValuePicker_toolbar');
  var tmp = $('.dataTables_filter').clone(true);
  $('.dataTables_filter').remove();
  tmp.prependTo(gToolbar);
  
  // buildDropDownFilter
  gToolbar.prepend('<div id="SimplejQueryDataTablesGadget_EnteredValuePicker_dropdown_wrapper"></div>');
  SimplejQueryDataTablesGadget.buildDropDownFilters();
  
  // reset button
  gToolbar.prepend('<input id="SimplejQueryDataTablesGadget_EnteredValuePicker_reset" accesskey="R" type="reset" />');
  gResetBtn = $('#SimplejQueryDataTablesGadget_EnteredValuePicker_reset');
  gResetBtn.click(function(){
    $.each( gPrefs.getArray("filterable"), function(){
      gTable.fnFilter('',this);
    } );
    gTable.fnFilter('');
    $('#SimplejQueryDataTablesGadget_EnteredValuePicker_dropdown_wrapper option').show();
  });

  // table toggle button
  gToolbar.prepend('<input type="button" id="SimplejQueryDataTablesGadget_EnteredValuePicker_toggle" value="'+gMsges['toggle_show']+'" />');
  gToggleBtn = $('#SimplejQueryDataTablesGadget_EnteredValuePicker_toggle');
  gToggleBtn.click(function(){
    gTable.toggle(0, function(){
      gToggleBtn.val( gToggleBtn.val()== gMsges['toggle_show'] ? gMsges['toggle_hide'] : gMsges['toggle_show'] );
      gadgets.window.adjustHeight();
      //gadgets.window.adjustHeight('40px');
    });
  });
  
  // Setting toggle button
  gToolbar.prepend('<input type="button" id="SimplejQueryDataTablesGadget_EnteredValuePicker_setting_toggle" value="'+gMsges['setting_toggle']+'" />');
  gSettingBtn = $('#SimplejQueryDataTablesGadget_EnteredValuePicker_setting_toggle');
  gSettingBtn.click(function(){
    $('#SimplejQueryDataTablesGadget_EnteredValuePicker_setting').toggle();
  });
  
  gTable.find('tbody').click(function(e){
    var tr = $(e.target).parents('tr');
    if( ! tr.hasClass('row_selected'))
      $('.row_selected').removeClass('row_selected');
    tr.toggleClass('row_selected');
  });
},

buildDropDownFilters: function(){
  $.each( gPrefs.getArray("filterable"), function(){
    SimplejQueryDataTablesGadget.buildDropDownFilter(this);
  } );
},

buildDropDownFilter: function(col){
  var dropId = 'SimplejQueryDataTablesGadget_EnteredValuePicker_dropdown_' + col;
  if( $('#'+dropId).length || typeof(col)=='undefined' ) return;
  $('#SimplejQueryDataTablesGadget_EnteredValuePicker_dropdown_wrapper').append('<select id="'+dropId+'" class="dropdown_filter"><option value="">ALL</option></select>');
  var dropdown = $('#'+dropId).data('dropColumn', col);
  var html = [];
  var coldata = [];
  var rows = gTable.fnSettings().aiDisplayMaster;
  for (var i=0, c=rows.length; i < c; i++) {
		var iRow = rows[i];
		var aData = gTable.fnGetData(iRow);
		var sValue = aData[col];
		if( $.inArray(sValue, coldata ) > -1 ) continue;
		else coldata.push(sValue);
	}
  $.each(coldata, function(){
    html.push('<option value="'+ this.replace('&', '&amp;') +'">'+ this +'</option>');
  });
  dropdown.append(html.join(''));
  dropdown.change(function(){
    var val = $(this).val();
    gTable.fnFilter( val, col );

    $(this).data('dropfiltered', 1);
    $('#SimplejQueryDataTablesGadget_EnteredValuePicker_dropdown_wrapper select').each(function(){
      if( true ) {
        var column = $(this).data('dropColumn');
        var settings = gTable.fnSettings();
        var rows = settings.aiDisplay;
        var columnData = [];
        for(var i = 0, c = rows.length ; i < c ; i++ ){
          var row = rows[i];
          var data = gTable.fnGetData(row);
          var value = data[column];
          if($.inArray(value, columnData) > -1) continue;
          else columnData.push(value);
        }
        $(this).find('option:gt(0)').each(function(){
          if( $.inArray($(this).val(), columnData) < 0){
            $(this).hide();
          }
          else
            $(this).show();
        });
        $(this).data('dropfiltered', 1);
      }
    });

  });
}

};